<template>
  <div class="commen-container">
    <h1>教学方向及知识点</h1>
    <div>
      <el-button size="normal" icon="el-icon-circle-plus" @click="showAddDialog">
        新增方向
      </el-button>
    </div>
    <div style="display: flex">
      <div style="flex: 1">
        <el-tree
          class="filter-tree"
          :data="tableData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
          ref="tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="data.children && data.children.length > 0">
              <el-button
                type="text"
                size="normal"
                @click.stop="() => showAddDialog(data)"
                icon="el-icon-circle-plus-outline">
              </el-button>
              <el-button
                type="text"
                size="normal"
                @click.stop="() => confirmDelete(node, data)"
                icon="el-icon-delete">
              </el-button>
              <el-button
                type="text"
                size="normal"
                @click.stop="() => showEditDialog(data)"
                icon="el-icon-edit">
              </el-button>
            </span>
            <span v-else>
              <el-button
                type="text"
                size="mini"
                @click.stop="() => confirmDelete(node, data)"
                icon="el-icon-delete">
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click.stop="() => showEditDialog(data)"
                icon="el-icon-edit">
              </el-button>
            </span>
          </span>
        </el-tree>
      </div>
      <el-divider direction="vertical"></el-divider>
      <div class="content juzhong" style="flex: 2">
        <h2 style="margin: 20px">
          {{
            direction.direction_title
          }}
        </h2>
        <div style="margin: 20px">
          {{ direction.description || '暂无描述' }}
        </div>
        <img
          :src="direction.image "
          style=" width: 400px;object-fit: cover"/>
        <el-button @click="showEditDialog(direction)">修改</el-button>
      </div>
    </div>

    <!-- 添加弹窗 -->
    <el-dialog
      title="添加知识点"
      :visible.sync="addDialogVisible"
      width="500px">
      <el-form :model="addForm" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="addForm.point_content"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑教学方向/知识点"
      :visible.sync="editDialogVisible"
      width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="ID">
          <el-input v-model="editForm.direction_id ? editForm.direction_id : editForm.point_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="editForm.label"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPoint,
  createDirection, getDirection, getDirectionandPoints
} from "@/api/home/direction";
import {Message} from "element-ui";

export default {
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableData: null,
      direction_id: null,
      direction: {},
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        direction_id: null,
        point_id: null,
        point_content: '',
        description: ''
      },
      editForm: {
        direction_id: null,
        point_id: null,
        label: '',
        description: ''
      },
      parentNode: null
    };
  },
  methods: {
    async fetchTable() {
      try {
        const rep = await getDirectionandPoints({direction_id: this.direction_id});
        this.tableData = rep;
      } catch (e) {
        console.log(e);
        Message.warning("查询无效！");
      }
    },
    async fetchDirection(id) {
      try {
        const rep = await getDirection({direction_id: id});
        this.direction = rep;
        console.log("方向", this.direction);
      } catch (e) {
        console.log(e);
        Message.warning("查询无效！");
      }
    },
    handleNodeClick(data) {
      console.log(JSON.stringify(data));
      this.fetchDirection(data.direction_id || data.point_id);
    },
    showAddDialog(parentData) {
      this.addDialogVisible = true;
      this.addForm = {
        direction_id: parentData.direction_id,
        point_id: null,
        label: '',
        description: ''
      };
      this.parentNode = parentData;
    },
    async handleAddSubmit() {
      try {
        const response = await addPoint(this.addForm);
        if (this.parentNode) {
          if (!this.parentNode.children) {
            this.$set(this.parentNode, 'children', []);
          }
          this.parentNode.children.push(response);
        } else {
          this.tableData.push(response);
        }
        Message.success('添加成功');
        this.addDialogVisible = false;
      } catch (e) {
        console.log(e);
        Message.warning('添加失败');
      }
    },
    showEditDialog(data) {
      this.editDialogVisible = true;
      this.editForm = {
        direction_id: data.direction_id,
        point_id: data.point_id,
        label: data.label,
        description: data.description
      };
    },
    async handleEditSubmit() {
      try {
        await updateDirection(this.editForm);
        const node = this.findNodeById(this.tableData, this.editForm.direction_id || this.editForm.point_id);
        if (node) {
          node.label = this.editForm.label;
          node.description = this.editForm.description;
        }
        if (this.direction.direction_id === this.editForm.direction_id || this.direction.point_id === this.editForm.point_id) {
          this.direction = {...this.editForm};
        }
        Message.success('编辑成功');
        this.editDialogVisible = false;
      } catch (e) {
        console.log(e);
        Message.warning('编辑失败');
      }
    },
    async confirmDelete(node, data) {
      MessageBox.confirm('确定要删除该教学方向/知识点吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.handleDelete(node, data);
      }).then(() => {
        Message.success('删除成功');
        if (this.direction.direction_id === data.direction_id || this.direction.point_id === data.point_id) {
          this.direction = {};
        }
      }).catch(() => {
        Message.info('已取消删除');
      });
    },
    async handleDelete(node, data) {
      try {
        const idToDelete = data.direction_id || data.point_id;
        await deleteDirection(idToDelete);
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => (d.direction_id === idToDelete) || (d.point_id === idToDelete));
        children.splice(index, 1);
      } catch (e) {
        console.log(e);
        Message.warning('删除失败');
      }
    },
    findNodeById(nodes, id) {
      for (let i = 0; i < nodes.length; i++) {
        if ((nodes[i].direction_id === id) || (nodes[i].point_id === id)) {
          return nodes[i];
        }
        if (nodes[i].children) {
          const found = this.findNodeById(nodes[i].children, id);
          if (found) {
            return found;
          }
        }
      }
      return null;
    }
  },
  mounted() {
    this.fetchTable();
    this.fetchDirection(1);
  }
};
</script>

<style scoped lang="scss">
.el-divider--vertical {
  height: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.content {
  padding: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
</style>
